from django.forms import model_to_dict
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import *
from django.contrib.auth.models import User


class LoginSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        data['refresh'] = str(refresh)
        data['access'] = str(refresh.access_token)
        data['token'] = data['access']
        del data['access']
        del data['refresh']
        data['username'] = self.user.username
        data['id'] = self.user.id
        data["roles"] = self.user.groups.values_list('name', flat=True)
        return data


class SurveySerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['submit_count'] = instance.submitsurvey_set.count()
        return ret

    class Meta:
        model = Survey
        fields = '__all__'


class SubmitSurveySerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['user'] = instance.user.username
        ret['survey'] = instance.survey.title
        ret['logic'] = instance.survey.logic
        return ret

    class Meta:
        model = SubmitSurvey
        fields = '__all__'


class ImageSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret["name"] = str(instance.file).replace("image/", "")
        return ret

    class Meta:
        model = Image
        fields = '__all__'


class FileSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret["name"] = str(instance.file).replace("file/", "")
        return ret

    class Meta:
        model = File
        fields = '__all__'




class UserSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret["roles"] = instance.groups.values_list('name', flat=True)
        ret.pop('password')
        return ret

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'is_staff', 'is_superuser')
